import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Divider, Space, Select } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import './Register.scss';

const { Option } = Select;

const Register = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { register } = useAuth();
  const [loading, setLoading] = useState(false);
  const [agreed, setAgreed] = useState(false);

  const handleSubmit = async (values) => {
    if (!agreed) {
      message.error('请先同意用户协议和隐私政策');
      return;
    }

    setLoading(true);
    try {
      const result = await register(values);
      if (result.success) {
        navigate('/');
      }
    } catch (error) {
      console.error('注册错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // const handleSendCode = async () => {
  //   try {
  //     const account = form.getFieldValue('email') || form.getFieldValue('mobile');
  //     if (!account) {
  //       message.error('请先输入邮箱或手机号');
  //       return;
  //     }

  //     const type = account.includes('@') ? 'email' : 'mobile';
  //     // await authAPI.sendCode({ account, type });
  //     message.success('验证码已发送');
  //   } catch {
  //     message.error('发送验证码失败');
  //   }
  // };

  return (
    <div className="register-page">
      <div className="register-container">
        <Card className="register-card">
          <div className="register-header">
            <h2>创建账户</h2>
            <p>加入思研社，开启学习之旅</p>
          </div>

          <Form
            form={form}
            name="register"
            onFinish={handleSubmit}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="username"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 3, max: 20, message: '用户名长度为3-20位' },
                { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
              ]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="用户名"
              />
            </Form.Item>

            <Form.Item
              name="nickname"
              rules={[
                { required: true, message: '请输入昵称' },
                { max: 20, message: '昵称不能超过20位' },
              ]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="昵称"
              />
            </Form.Item>

            <Form.Item
              name="email"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '邮箱格式不正确' },
              ]}
            >
              <Input
                prefix={<MailOutlined />}
                placeholder="邮箱"
              />
            </Form.Item>

            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
              ]}
            >
              <Input
                prefix={<PhoneOutlined />}
                placeholder="手机号"
              />
            </Form.Item>

            <Form.Item
              name="role"
              rules={[
                { required: true, message: '请选择角色' },
              ]}
            >
              <Select placeholder="选择角色">
                <Option value="student">学生</Option>
                <Option value="teacher">教师</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, max: 20, message: '密码长度为6-20位' },
                // { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]/, message: '密码必须包含字母和数字' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
              />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              dependencies={['password']}
              rules={[
                { required: true, message: '请确认密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="确认密码"
              />
            </Form.Item>

            <Form.Item>
              <div className="agreement">
                <input
                  type="checkbox"
                  id="agreement"
                  checked={agreed}
                  onChange={(e) => setAgreed(e.target.checked)}
                />
                <label htmlFor="agreement">
                  我已阅读并同意
                  <Link to="/terms" target="_blank">《用户协议》</Link>
                  和
                  <Link to="/privacy" target="_blank">《隐私政策》</Link>
                </label>
              </div>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                block
                className="register-button"
              >
                注册
              </Button>
            </Form.Item>

            <div className="login-link">
              已有账户？ <Link to="/login">立即登录</Link>
            </div>
          </Form>
        </Card>
      </div>
    </div>
  );
};

export default Register; 